<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,
        addPermi: ['platform:tenant:add'],
      }"
      :table-props="{
        selection: false,
        delBtn: false,
        viewBtn: false,
        editBtn: true,
        menuSlot: true,
        menuWidth: 300,
        editPermi: ['platform:tenant:edit'],
      }"
      :form-props="{
        labelWidth: '140px',
      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @openBeforeFun="openBeforeFun"
    >
      <template #rightToolbar></template>
      <template #menuSlot="scope:any">
        <div class="menu-btn" v-has-permi="['platform:tenant:delete']" v-if="scope.row.id !== constants.DEFAULT_TENANT_ID">
          <el-tooltip class="box-item" effect="dark" :content="t('crud.deleteText')" placement="top">
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
          </el-tooltip>
          <el-divider direction="vertical" />
        </div>
        <div class="menu-btn" v-has-permi="['platform:tenant:edit']" v-if="scope.row.id !== constants.DEFAULT_TENANT_ID">
          <el-tooltip class="box-item" effect="dark" :content="t('platform.tenant.action.resetPwd')" placement="top">
            <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)" />
          </el-tooltip>
          <el-divider direction="vertical" />
        </div>

        <div class="menu-btn" v-has-permi="['platform:tenant:edit']" v-if="scope.row.id !== constants.DEFAULT_TENANT_ID">
          <el-tooltip class="box-item" effect="dark" :content="t('platform.tenant.action.sync')" placement="top">
            <el-button link type="primary" icon="Refresh" @click="handleSyncTenantPackage(scope.row)" />
          </el-tooltip>
          <el-divider direction="vertical" />
        </div>
      </template>
      <template #status="scope:any">
        <el-switch v-model="scope.row.status" active-value="Enabled" inactive-value="Disabled" @change="handleStatusChange(scope.row)" />
      </template>
    </yt-crud>
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import { listTenant, delTenant, saveTenant, changeStatus, syncTenantPackage, resetAdminPwd } from '@/api/system/tenant'
import YtCrud from '@/components/common/yt-crud.vue'
import {ComponentInternalInstance} from 'vue'
import {useI18n} from 'vue-i18n'
import {optionSelect as tenantPackageOptionSelect } from '@/api/system/tenantPackage'
import {TenantVo} from '@/api/system/tenant/types'
import {to} from 'await-to-js'
import constants from '@/constants'
import {parseTime} from '@/utils/ruoyi'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum'))
const { t } = useI18n()

const state = reactive({
  page: {
    pageSize: 12,
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {},
})


const tenantPackageOptions = ref<any[]>([])

// 字典
const column = ref<IColumn[]>([
  {
    label: t('platform.tenant.id'),
    key: 'id',
    search: true,
    type: 'string',
    formHide: true,
    colSpan: 21,
  },
  {
    label: t('platform.tenant.companyName'),
    key: 'companyName',
    type: 'string',
    search: true,
    formHide: false,
    colSpan: 21,
    searchLabelWidth: 120,
    rules: [{ required: true, message: t('platform.tenant.validator.companyName')}],
  },
  {
    label: t('platform.tenant.contactUserName'),
    key: 'contactUserName',
    type: 'string',
    search: false,
    formHide: false,
    colSpan: 21,
    rules: [{ required: true, message: t('platform.tenant.validator.contactUserName')}],
  },
  {
    label: t('platform.tenant.contactPhone'),
    key: 'contactPhone',
    type: 'string',
    search: false,
    hide: false,
    formHide: false,
    editHide: false,
    colSpan: 21,
    rules: [{ required: true, message: t('platform.tenant.validator.contactPhone')}],
  },
  {
    label: t('platform.tenant.username'),
    key: 'username',
    type: 'string',
    hide: true,
    search: false,
    formHide: false,
    editHide: true,
    colSpan: 21,
    rules: [
      { required: true, message: t('platform.tenant.validator.username')},
      { min: 3, max: 32, message: t('platform.tenant.validator.username')},
    ],
  },
  {
    label: t('platform.tenant.password'),
    key: 'password',
    type: 'string',
    hide: true,
    search: false,
    formHide: false,
    editHide: true,
    colSpan: 21,
    rules: [
      { required: true, message: t('platform.tenant.validator.password')},
      { min: 6, max: 32, message: t('platform.tenant.validator.password')},
    ],
    componentProps: {

    }
  },
  {
    label: t('platform.tenant.packageId'),
    key: 'packageId',
    type: 'select',
    hide: true,
    search: false,
    formHide: false,
    editHide: true,
    componentProps: {
      keyAlias: 'id',
      valueAlias: 'id',
      labelAlias: 'name',
      options: tenantPackageOptions,
      style: 'width: 100%',
    },
    colSpan: 21,
    rules: [{ required: true, message: t('platform.tenant.validator.packageId')}],
  },
  {
    label: t('platform.tenant.platformProfitPercent'),
    key: 'platformProfitPercent',
    type: 'number',
    search: false,
    formHide: false,
    colSpan: 21,
    rules: [
      { required: true, message: t('platform.tenant.validator.platformProfitPercent') },
    ],
    componentProps: {
      min: 0.00,
      max: 1.00,
      step: 0.01,
      precision: 2,
      style: {
        width: '100%'
      }
    },
  },
  {
    label: t('platform.tenant.expireTime'),
    key: 'expireTime',
    type: 'date',
    hide: false,
    search: false,
    formHide: false,
    editHide: false,
    colSpan: 21,
    componentProps: {
      style: 'width: 100%',
    },
    rules: [{ required: true, message: t('platform.tenant.validator.expireTime')}],
  },
  {
    label: t('platform.tenant.avatar'),
    key: 'avatar',
    type: 'image',
    hide: true,
    search: false,
    formHide: false,
    editHide: false,
    componentProps: {
      limit: 1,
      isShowTip: true,
      uploadType: 'url',
    },
    colSpan: 21,
  },
  {
    label: t('platform.tenant.displayName'),
    key: 'displayName',
    type: 'string',
    hide: true,
    search: false,
    formHide: false,
    editHide: false,
    colSpan: 21,
  },
  {
    label: t('platform.tenant.domain'),
    key: 'domain',
    type: 'string',
    hide: true,
    search: false,
    formHide: false,
    editHide: false,
    colSpan: 21,
  },

  {
    label: t('platform.tenant.accountCount'),
    key: 'accountCount',
    type: 'number',
    hide: true,
    search: false,
    formHide: false,
    editHide: false,
    colSpan: 21,
    componentProps: {
      min: -1,
      max: 999999,
      step: 1,
      precision: 0,
      style: {
        width: '100%'
      }
    },
  },
  {
    label: t('platform.tenant.status'),
    key: 'status',
    type: 'select',
    componentProps: {
      options: EnableStatusEnum,
    },
    search: true,
    formHide: true,
    slot: true,
  },
  {
    label: t('crud.table.column.note'),
    key: 'note',
    hide: true,
    formHide: false,
    componentProps: {
      type: 'textarea',
      rows: 2,
    },
    colSpan: 21,
  },
  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
])

const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  listTenant({
    ...state.page,
    ...state.query,
  })
    .then((res: any) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

const getDict = () => {
  tenantPackageOptionSelect().then((res)=>{
    tenantPackageOptions.value = res.data
  })
}
getDict()

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true
  saveTenant(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

// 弹窗前置操作
const openBeforeFun = ({ type, data }) => {
  if (type === 'add') {
    data.accountCount = -1
    let currentDate = new Date()
    const oneYearLater = new Date(currentDate)
    oneYearLater.setFullYear(oneYearLater.getFullYear() + 1)
    oneYearLater.setDate(oneYearLater.getDate() - 1)
    data.expireTime = parseTime(oneYearLater.getTime(), '{y}-{m}-{d}')
  } else {
    data.platformProfitPercent = Number(data.platformProfitPercent)
  }
}

// 删除
const handleDelete = async (row: any) => {
  ElMessageBox.confirm(
    t('platform.tenant.tooltip.delete'),
    t('operate.confirm.delete'),
    {
      type: 'warning',
    }
  )
  .then(() => {
    state.loading = true
    delTenant(row.id).then(() => {
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(() => {
      state.loading = false
    })
  })
}

/** 状态修改  */
const handleStatusChange = async (row: any) => {
  if(!row.id)  return
  try {
    await proxy?.$modal.confirm(row.status === 'Enabled' ? t('crud.action.tooltip.enable') : t('crud.action.tooltip.disabled'))
    await changeStatus(row.id, row.status)
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  } catch (err) {
    row.status = row.status === 'Enabled' ? 'Disabled' : 'Enabled'
  }
}



/** 重置密码按钮操作 */
const handleResetPwd = async (row: TenantVo) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入"' + row.companyName + '"管理员的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
    })
  )
  if (!err) {
    await resetAdminPwd(row.id, res.value)
    proxy?.$modal.msgSuccess('修改成功，新密码是：' + res.value)
  }
}


/** 同步租户套餐按钮操作 */
const handleSyncTenantPackage = async (row: TenantVo) => {
  try {
    await proxy?.$modal.confirm('是否确认同步租户套餐租户编号为"' + row.tenantId + '"的数据项？')
    state.loading = true
    await syncTenantPackage(row.tenantId, row.packageId)
    getData()
    proxy?.$modal.msgSuccess('同步成功')
  } catch {
    return
  } finally {
    state.loading = false
  }
}


const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>

<style lang="scss" scoped></style>
